import plugin from '../../../lib/plugins/plugin.js'
import Mc from "../components/Code.js";
import mcConfig from "../components/mcConfig.js";
import Render from '../model/render.js'

export class tili extends plugin {
    constructor() {
        super({
            name: "鸣潮-体力查询",
            event: "message",
            priority: 666666,
            rule: [
                {
                    reg: "^#?(mingchao|明朝|鸣潮)?(体力|日常数据)$",
                    fnc: "querySanity"
                }
            ]
        })
    }

    async querySanity(e) {
        let accountList = JSON.parse(await redis.get(`Yunzai:mingchao:users:${e.user_id}`)) || await mcConfig.getUserConfig(e.user_id);

        if (!accountList || !accountList.length) {
            return await e.reply('当前没有绑定任何账号，请使用[#鸣潮登录]进行绑定\n具体查看#鸣潮帮助');
        }

        const mc = new Mc();
        let data = [];
        let deleteroleId = [];

        for (let account of accountList) {
            const usability = await mc.isAvailable(account.token);

            if (!usability) {
                data.push({ message: `账号 ${account.roleId} 的鸣潮Token已失效\n请重新绑定鸣潮Token\n具体查看#鸣潮帮助` });
                deleteroleId.push(account.roleId);
                continue;
            }

            const gameData = await mc.getGameData(account.token);

            if (!gameData.status) {
                data.push({ message: gameData.msg });
            } else {
                const imageCard = await Render.dailyData(gameData.data)
                data.push({ message: imageCard });
            }
        }

        if (deleteroleId.length) {
            let newAccountList = accountList.filter(account => !deleteroleId.includes(account.roleId));
            mcConfig.setUserConfig(e.user_id, newAccountList);
        }

        if (data.length === 1) {
            await e.reply(data[0].message);
            return true;
        }

        await e.reply(Bot.makeForwardMsg([{ message: `用户 ${e.user_id}` }, ...data]));
        return true;
    }

    async autoPush() {
        const { mingchao_auto_push_list: autoPushList } = mcConfig.getConfig();
        await Promise.all(autoPushList.map(async user => {
            const [botId, groupId, userId] = user.split(':');
            let accountList = JSON.parse(await redis.get(`Yunzai:mingchao:users:${userId}`)) || await mcConfig.getUserConfig(userId);
            if (!accountList.length) {
                return
            }

            const mc = new Mc();
            let data = [];
            let deleteroleId = [];

            for (let account of accountList) {
                const usability = await mc.isAvailable(account.token);

                if (!usability) {
                    data.push({ message: `账号 ${account.roleId} 的鸣潮Token已失效\n请重新绑定鸣潮Token\n具体查看#鸣潮帮助` });
                    deleteroleId.push(account.roleId);
                    continue;
                }

                const result = await mc.getGameData(account.token);

                if (!result.status) {
                    data.push({ message: result.msg })
                    return true;
                }

                const key = `Yunzai:mingchao:pushed:${result.data.roleId}`;
                const isPushed = await redis.get(key);
                const isFull = result.data.energyData.cur >= result.data.energyData.total;
                if (isFull && !isPushed) {
                    data.push({ message: `漂泊者${result.data.roleName}(${result.data.roleId})，你的鸣潮体力已经爆满了，快去看看吧` })
                    await redis.set(key, 'true');
                } else if (!isFull && isPushed) {
                    await redis.del(key);
                }
            }

            if (deleteroleId.length) {
                let newAccountList = accountList.filter(account => !deleteroleId.includes(account.roleId));
                mcConfig.setUserConfig(e.user_id, newAccountList);
            }

            if (data.length) {
                if (data.length === 1) {
                    if (groupId === "undefined") {
                        await Bot[botId]?.pickUser(userId).sendMsg(data[0].message)
                    } else {
                        await Bot[botId]?.pickGroup(groupId).sendMsg([segment.at(userId), data[0].message])
                    }
                    return true;
                } else {
                    if (groupId === "undefined") {
                        await Bot[botId]?.pickUser(userId).sendMsg(Bot.makeForwardMsg([{ message: `用户 ${userId}` }, ...data]))
                    } else {
                        await Bot[botId]?.pickGroup(groupId).sendMsg(segment.at(userId))
                        await Bot[botId]?.pickGroup(groupId).sendMsg(Bot.makeForwardMsg([{ message: `用户 ${userId}` }, ...data]))
                    }
                }
            }
            return true;
        }))
    }
}